package cn.chencq.moudle.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.chencq.constants.Constants;
import cn.chencq.constants.Constants.MenuType;
import cn.chencq.moudle.sys.dao.BaseDao;
import cn.chencq.moudle.sys.dao.SysMenuDao;
import cn.chencq.moudle.sys.entity.SysMenu;
import cn.chencq.moudle.sys.service.SysMenuService;
import cn.chencq.moudle.sys.service.SysUserService;

@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenu> implements SysMenuService {

	@Autowired
	private SysMenuDao sysMenuDao;
	
	@Autowired
	private SysUserService sysUserService;


	@Override
	protected BaseDao getBaseDao() {
		return this.sysMenuDao;
	}
	
	@Override
	public List<SysMenu> getUserMenuList(Long userId) {
		// 系统管理员，拥有最高权限
		if (userId == Constants.SUPER_ADMIN) {
			return getAllMenuList(null);
		}

		// 用户菜单列表
		List<Long> menuIdList = sysUserService.queryAllMenuId(userId);
		return getAllMenuList(menuIdList);
	}

	/**
	 * 获取所有菜单列表
	 */
	private List<SysMenu> getAllMenuList(List<Long> menuIdList) {
		// 查询根菜单列表
		List<SysMenu> menuList = queryListParentId(0L, menuIdList);
		// 递归获取子菜单
		getMenuTreeList(menuList, menuIdList);

		return menuList;
	}

	/**
	 * 递归
	 */
	private List<SysMenu> getMenuTreeList(List<SysMenu> menuList, List<Long> menuIdList) {
		List<SysMenu> subMenuList = new ArrayList<SysMenu>();

		for (SysMenu entity : menuList) {
			if (entity.getType() == MenuType.CATALOG.getValue()) {// 目录
				entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList), menuIdList));
			}
			subMenuList.add(entity);
		}

		return subMenuList;
	}

	@Override
	public List<SysMenu> queryNotButtonList() {
		return sysMenuDao.selectNotButtonList();
	}


	@Override
	public List<SysMenu> queryListParentId(Long parentId, List<Long> menuIdList) {
		List<SysMenu> menuList = queryListParentId(parentId);
		if(menuIdList == null){
			return menuList;
		}
		
		List<SysMenu> userMenuList = new ArrayList<SysMenu>();
		for(SysMenu menu : menuList){
			if(menuIdList.contains(menu.getMenuId())){
				userMenuList.add(menu);
			}
		}
		return userMenuList;
	}
	
	@Override
	public List<SysMenu> queryListParentId(long parentId) {
		return sysMenuDao.selectListParentId(parentId);
	}
}
